package com.cfg.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cfg.domain.DmCustomstats;
import com.cfg.mapper.DmCustomstatsMapper;
import com.common.core.domain.TreeSelect;
import com.common.core.domain.entity.SysDept;
import com.common.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class DmCustomstatsService extends ServiceImpl<DmCustomstatsMapper, DmCustomstats> {


    public List<DmCustomstats> buildDeptTreeSelect()
    {

        List<DmCustomstats> dmCustomstatsList=this.list();
        List<DmCustomstats> deptTrees = buildDeptTree(dmCustomstatsList);
        return  deptTrees;

    }

    public List<DmCustomstats> buildDeptTree(List<DmCustomstats> depts)
    {
        List<DmCustomstats> returnList = new ArrayList<DmCustomstats>();
        List<String> tempList = depts.stream().map(DmCustomstats::getId).collect(Collectors.toList());
        for (DmCustomstats dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getUpID()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }
    private void recursionFn(List<DmCustomstats> list, DmCustomstats t)
    {
        // 得到子节点列表
        List<DmCustomstats> childList = getChildList(list, t);
        t.setChildren(childList);
        for (DmCustomstats tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    /**
     * 得到子节点列表
     */
    private List<DmCustomstats> getChildList(List<DmCustomstats> list, DmCustomstats t)
    {
        List<DmCustomstats> tlist = new ArrayList<DmCustomstats>();
        Iterator<DmCustomstats> it = list.iterator();
        while (it.hasNext())
        {
            DmCustomstats n = (DmCustomstats) it.next();
            if (StringUtils.isNotNull(n.getUpID()) && n.getUpID().equals(t.getId()) )
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<DmCustomstats> list, DmCustomstats t)
    {
        return getChildList(list, t).size() > 0;
    }

}
